<?php
namespace app\index\controller;

use app\common\model\coin\CoinUser;
use app\common\model\coin\CoinList;
use think\Exception;
use think\Config;
use app\common\controller\Base64;
use app\common\controller\Param;
use app\common\model\cash\CashRecharge;
use think\Db;
use app\common\model\cash\CashList;
use app\common\controller\Finance;
use app\common\model\user\Users;

class Coin extends Base
{
	/**
	 * 用户参数
	 * @var unknown
	 */
	private $param;
	
	/**
	 * 构造函数
	 * {@inheritDoc}
	 * @see \app\index\controller\Base::_initialize()
	 */
	public function _initialize()
	{
		parent::_initialize();
		$this->param = Param::getParam($this->user_id);
	}
	/**
	 * 传递用户参数
	 * @return unknown
	 */
	public function getParam()
	{
		return jsonSuccess($this->param);
	}
	
	/**
	 * 获取用户所有的币种
	 * @return unknown
	 */
	public function getUserCoin()
	{
		//获取用户的所有币种列表
		$list = CoinUser::where(['user_id' => $this->user_id , 'state' => 1])->select();
		foreach ($list as $rows) {
			$rows['coin'] = CoinList::get($rows['coin_id']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 添加币种
	 * @throws Exception
	 * @return unknown
	 */
	public function addUserCoin()
	{
		$data = $this->reqeust->post('');
		try {
			if(!$data['name'])throw new Exception('请输入币种名称');
			if(!$data['address'])throw new Exception('请输入提币地址');
			$coin_id = CoinList::where(['state' => 1,'name' => $data['name']])->value('id');
			if(!$coin_id)throw new Exception('输入的币种不存在');
			$info = [
					'user_id' => $this->user_id,
					'coin_id' => $coin_id,
					'address' => $data['address'],
					'create_time' => time(),
					'update_time' => time()
			];
			if(CoinUser::where(['user_id' => $this->user_id,'coin_id' => $coin_id,'state' => 1])->value('id'))
				throw new Exception('该币种账户已存在');
			CoinUser::create($info);
		} catch (Exception $e) {
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加账户成功');
	}
	
	/**
	 * 上传打款截图
	 * @throws Exception
	 * @return unknown
	 */
	public function upPayImg()
	{
		//获取客户端传递的临时文件
		if(!empty($_FILES['file'])){
			$file = $_FILES['file'];
			$upload = new Base64();
			try {
				$res = $upload->uniAppUpload(Config::get('path.recharge'), $file);
				if(!$res)throw new Exception('图片上传失败');
			} catch (Exception $e) {
				return jsonError($e->getMessage());
			}
			return jsonSuccess($res);
		}
	}
	
	/**
	 * 充币
	 * @throws Exception
	 * @return unknown
	 */
	public function recharge()
	{
		$data = $this -> reqeust -> post('');
		try {
			//验证数据的合法性
			if(!$data['coin_id'])throw new Exception('请选择币种');
			if(!$data['num'])throw new Exception('请输入充值数量');
 			if(!$data['pay_img'])throw new Exception('请上传打款截图');
			$coin_address = CoinList::where(['id' => $data['coin_id'] , 'state' => 1])->value('address');
			if(!$coin_address)throw new Exception('币种不存在');
			//判断数据是否符合后台配置参数
			if($this->param['invest_min_price'] > $data['num'])
				throw new Exception("最小充币数量为{$this->param['invest_min_price']}");
			//组装数据
			$res = [
					'user_id' => $this->user_id,
					'coin_id' => $data['coin_id'],
					'num' => $data['num'],
					'address' => $coin_address,
					'pay_img' => $data['pay_img'],
					'create_time' => time(),
					'update_time' => time()
			];
			CashRecharge::create($res);
		} catch (Exception $e){
			return jsonError($e->getMessage());
		}
		return jsonSuccess('充币提交成功');
	}
	
	/**
	 * 充币记录列表
	 * @return unknown
	 */
	public function rechargeList()
	{
		$data = $this->reqeust->post(''); //获取客户端传递的数据
		$where = ['user_id' => $this->user_id]; //初始化查询条件
		if(!empty($data['coin_id']))$where['coin_id'] = $data['coin_id'];
		$list = CashRecharge::where($where)->order('id desc')->paginate();
		return jsonSuccess($list);
	}
	
	/**
	 * 提交提币申请
	 * @throws Exception
	 * @return unknown
	 */
	public function cash()
	{
		$data = $this->reqeust->post('');
		Db::startTrans();
		try {
			//redis验证提币状态
			if($this->redis->get('user'.$this->user_id))
				throw new Exception('请勿重复提交');
			//开启设置redis验证
			$this->redis->set('user'.$this->user_id,1);
			//判断数据合法性
			if(!$data['pay_pwd'])throw new Exception('请输入交易密码');
			if(!$data['coin_id'])throw new Exception('请选择提币币种');
			if(!$data['num'])throw new Exception('请输入提币数量');
			if(!$data['address'])throw new Exception('请输入提币地址');
			//判断提币是否符合后台参数
			if($data['num'] < $this->param['cash_nim_price'])
				throw new Exception("最小提币数量为{$this->param['cash_nim_price']}");
			if($data['num'] > $this->param['cash_max_price'])
				throw new Exception("最大提币数量为{$this->param['cash_max_price']}");
			if($this->param['cash_multi'] && $data['num'] % $this->param['cash_multi'] > 0)
				throw new Exception('提币数量不正确');
			//判断余额是否足够
			$avalible_price = CoinUser::where(['user_id' => $this->user_id , 'coin_id' => $data['coin_id']])->value('avalible_price');
			if($avalible_price < $data['num'])
				throw new Exception('账户余额不足');
				$cash_day = CashList::where([
						'user_id' => $this->user_id,
						'state' => ['neq',2],
						'create_time' => ['between',[strtotime(date('Y-m-d').'00:00:00'),strtotime(date('Y-m-d').'23:59:59')]]
				])->count();
				if($cash_day)throw new Exception('每日只能提现一笔');
			$user = Users::get($this->user_id);
			if(md5($data['pay_pwd']) != $user->pay_pwd)throw new Exception('交易密码不正确');
			//修改用户钱包
			CoinUser::where(['user_id' => $this->user_id , 'coin_id' => $data['coin_id']])->setDec('avalible_price',$data['num']);
			CoinUser::where(['user_id' => $this->user_id , 'coin_id' => $data['coin_id']])->setInc('freezing_price',$data['num']);
			//重组提币数据
			$res = [
					'user_id' => $this->user_id,
					'coin_id' => $data['coin_id'],
					'num' => $data['num'],
					'fee' => $this->param['cash_fee'],
					'ready_num' => $data['num'] - $this->param['cash_fee'],
					'surplus_num' => CoinUser::where(['user_id' => $this->user_id , 'coin_id' => $data['coin_id']])->value('avalible_price'),
					'address' => $data['address'],
					'create_time' => time(),
					'update_time' => time()
			];
			//提交提币申请
			CashList::create($res);
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			$this->redis->delete('user'.$this->user_id);
			return jsonError($e->getMessage());
		}
		//清除redis验证
		$this->redis->delete('user'.$this->user_id);
		return jsonSuccess('提币申请成功');
	}
	
	/**
	 * 提币记录列表
	 * @return unknown
	 */
	public function cashList()
	{
		$data = $this->reqeust->post(''); //获取客户端传递的数据
		$where = ['user_id' => $this->user_id]; //初始化查询条件
		if(!empty($data['coin_id']))$where['coin_id'] = $data['coin_id'];
		$list = CashList::where($where)->order('id desc')->paginate();
		return jsonSuccess($list);
	}
}